//
//  ZCEnrollVC.m
//  zctx
//
//  Created by apple on 16/2/22.
//  Copyright © 2016年 sanliang. All rights reserved.
//

#import "ZCEnrollVC.h"
#import "ZCEnrollButtonView.h"
#import "ZCEnrollView.h"

#import "ZCRankingDeatailView.h" //用户View
#import "YYaoViewController.h" //抽奖 - 摇一摇
#import "FSMediaPicker.h" //获取图片
#import "ZCEnrollModelContent.h" //报名资料Model
#import "ZCRankingListModelContent.h" //报名资料详情
#import "ActionView.h" //分享

#define ItemWidth 55
#define ItemHeight 55
#define MaxItemCount 1
#define MaxLableHeight 30
@interface ZCEnrollVC()<UIScrollViewDelegate,ZCEnrollViewPhotoViewDelegate,FSMediaPickerDelegate,MessagePhotoItemDelegate>
{
    NSInteger imageCount;
    NSMutableArray *ImgArray;
}
@property (nonatomic,strong)UIScrollView *scrolloView;
@property (nonatomic,strong)UIImageView *imageView;
@property (nonatomic,strong)UIView *enrollView;  //报名footerView
@property (nonatomic,strong)UIView *baoMingView;  //报名View
@property (nonatomic,strong)UIButton *selectBut;
@property (nonatomic,strong)UILabel *labelTitle;    //上传图片Lable
@property (nonatomic,strong)UIView *photoScrollView; //图片选择View

@property (nonatomic,strong)NSArray *contentArray;  //宣言默认内容数组
@property (nonatomic,strong)NSMutableArray *ButtonArray; //宣言按钮数组
@property (nonatomic,strong)NSMutableArray *infoArray;  //个人信息
@property (nonatomic,strong)NSMutableArray *textfiledArray; //宣言textfiled数组
@property (nonatomic,strong)NSString *sloganStr;  //宣言
@property (nonatomic,strong)NSString *voteStr;  //报名id
@end

@implementation ZCEnrollVC

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    self.view.shiftHeightAsDodgeViewForMLInputDodger = 50.0f;
    [self.view registerAsDodgeViewForMLInputDodger];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];

}

-(void)viewDidLoad{
    self.view.backgroundColor = [UIColor colorWithHexString:@"#F1FBFE"];
    imageCount = 0;

    self.ButtonArray = [[NSMutableArray alloc] init];
    ImgArray = [[NSMutableArray alloc]init];
    self.sloganStr = @"食品安全我做主!";
    self.edgesForExtendedLayout = UIRectEdgeNone;
    [self.view addSubview:self.scrolloView];
    if (([[[UIDevice currentDevice] systemVersion] floatValue] >=9.0)
        ) {
        [self.scrolloView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view).with.insets(UIEdgeInsetsMake(0, 0,0, 0));
        }];
    }else{
        [self.scrolloView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view).with.insets(UIEdgeInsetsMake(64,0,0, 0));
        }];
    }
    [self.scrolloView addSubview:self.imageView];
    self.imageView.frame = CGRectMake(0,0,SCREEN_WIDTH,192);
    
    NSString *voteid = [NSString stringWithFormat:@"%.0f",theAppdelegate.moreModel.voteid];
    
    NSLog(@"voteid = %@",voteid);
    if (theAppdelegate.moreModel.voteid ==0) {
        //未报名
        self.baoMingView = [[UIView alloc]initWithFrame:CGRectMake(0,192,SCREEN_WIDTH, 720)];
        [self.scrolloView addSubview:self.baoMingView];
        [self addOtherView];
        [self requestStudentData];
    }else{
//        已报名
        self.voteStr = [NSString stringWithFormat:@"%.0f",theAppdelegate.moreModel.voteid];
        [self requestVotedetail];//请求已报名信息
    }
}

#pragma mark 获取学生资料
-(void)requestStudentData{
    [NetworkManager requestAcsuzhouXwsMemberInfomid:UserModel.mid password:UserModel.password success:^(NSDictionary *dictResponse) {
        if ([[dictResponse objectForKey:@"content"] isKindOfClass:[NSDictionary class]]){
            NSDictionary *dict = (NSDictionary *)[dictResponse objectForKey:@"content"];
            ZCEnrollModelContent *contentModel = [ZCEnrollModelContent modelObjectWithDictionary:dict];
            NSMutableArray *datainfoArray = [NSMutableArray arrayWithObjects:contentModel.school,contentModel.grade,contentModel.classProperty,contentModel.name,nil];
            for (int i=0; i<4; i++) {
                UILabel *infoLable = (UILabel *)self.infoArray[i];
                [infoLable setText:[NSString stringWithFormat:@" %@",datainfoArray[i]]];
            }
        }
    } failure:^(NSError *error) {
        
    }];
}

-(void)addOtherView{
    //3按钮
    ZCEnrollButtonView *EnButton = [[ZCEnrollButtonView alloc]initWithFrame:CGRectMake(0,0, SCREEN_WIDTH,200) andType:@"1"];
    [self.baoMingView addSubview:EnButton];
    EnButton.Ebutton = ^(NSInteger num){
        NSLog(@"num = %ld",num);
    };
    EnButton.mModel = theAppdelegate.moreModel;
    //报名处
    self.enrollView = [[UIView alloc]initWithFrame:CGRectZero];
    [self.baoMingView addSubview:self.enrollView];
    self.enrollView.frame = CGRectMake(0,200,SCREEN_WIDTH,520);
    self.enrollView.backgroundColor = RGB(241, 251, 253);
    [self addLabelTitle];
    [self setup];
    [self OtherInfoLable];
    [self addSelectButton];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark  MessagePhotoViewDelegate
- (void)didSelecteZCEnrollViewPhotoMenuItem:(NSArray *)Array atIndex:(NSInteger)index{
    
    NSLog(@"2223333");
    imageCount = Array.count;
    FSMediaPicker *mediaPicker = [[FSMediaPicker alloc] init];
    mediaPicker.delegate = self;
    
    if (DEVICE_SYSTEM_VERSION) {
        [mediaPicker showFromView:self.view];
    }else{
        [mediaPicker showActionSheet:self.view];
    }
}

- (void)mediaPicker:(FSMediaPicker *)mediaPicker didFinishWithMediaInfo:(NSDictionary *)mediaInfo
{
//    NSLog(@"img222 = %@,count = %ld",mediaInfo.editedImage,ImgArray.count);
    UIImage *image = mediaInfo.editedImage;
    [ImgArray addObject:image];
    [self initlizerScrollView:ImgArray];
}

#pragma mark 上传头像
- (void)setup{
    _photoScrollView = [[UIView alloc]init];
    [self.enrollView addSubview:_photoScrollView];
    if (IS_IPHONE_4_OR_LESS ||IS_IPHONE_5) {
        [_photoScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.labelTitle.top).with.offset(-5);
            make.height.mas_equalTo(@(63));
            make.left.equalTo(self.labelTitle.right).with.offset(0);
            make.right.equalTo(self.enrollView.right).with.offset(0);
        }];
    }else{
        [_photoScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.labelTitle.top).with.offset(-5);
            make.height.mas_equalTo(@(63));
            make.left.equalTo(self.labelTitle.right).with.offset(0);
            make.right.equalTo(self.enrollView.right).with.offset(0);
        }];
    }
    
    [self initlizerScrollView:nil];
}

-(void)messagePhotoItemView:(MessagePhotoMenuItem *)messagePhotoItemView didSelectDeleteButtonAtIndex:(NSInteger)index{
    NSLog(@"index = %ld",index);
    [ImgArray removeObjectAtIndex:index];
    [self initlizerScrollView:ImgArray];
}

-(void)initlizerScrollView:(NSArray *)imgList{
    [self.photoScrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    CGFloat  itmWidth;
    if (IS_IPHONE_4_OR_LESS ||IS_IPHONE_5) {
        itmWidth = 45;
    }else{
        itmWidth = 55;
    }
    for(int i=0;i<imgList.count;i++){
        UIImage *image = [imgList objectAtIndex:i];
        MessagePhotoMenuItem *photoItem = [[MessagePhotoMenuItem alloc]initWithFrame:CGRectMake(i * (itmWidth+11),0, itmWidth, 63)];
        photoItem.delegate = self;
        photoItem.tag = i;
        photoItem.contentImage = image;
        [self.photoScrollView addSubview:photoItem];
    }
    if(imgList.count<MaxItemCount){
        UIButton *btnphoto=[UIButton buttonWithType:UIButtonTypeCustom];
        [btnphoto setFrame:CGRectMake( (itmWidth+11) * imgList.count,10, itmWidth, itmWidth)];//
        if (imgList.count==0) {
            [btnphoto setImage:[UIImage imageNamed:@"enroll_add_pic"] forState:UIControlStateNormal];
        }else{
            [btnphoto setImage:[UIImage imageNamed:@"raise_add"] forState:UIControlStateNormal];
        }
        btnphoto.tag = imgList.count;
        //给添加按钮加点击事件
        [btnphoto addTarget:self action:@selector(openMenu:) forControlEvents:UIControlEventTouchUpInside];
        [self.photoScrollView addSubview:btnphoto];
    }
}

-(void)openMenu:(UIButton*)sender{
    //在这里呼出下方菜单按钮项
     NSInteger index = sender.tag;
    [self didSelecteZCEnrollViewPhotoMenuItem:ImgArray atIndex:index];
//    if (_delegate && [_delegate respondsToSelector:@selector(didSelecteZCEnrollViewPhotoMenuItem:atIndex:)] ) {
//        NSInteger index = sender.tag;
//        [self.delegate didSelecteZCEnrollViewPhotoMenuItem:self.PicArray atIndex:index];
//    }
}

#pragma mark 学校、年级、班级、姓名、宣言
-(void)OtherInfoLable{
    NSArray *titleArray = [NSArray arrayWithObjects:@"学校:",@"年级:",@"班级:",@"姓名:",@"宣言:",nil];
    for(int i=0;i<5;i++){
        UILabel *titleLable = [[UILabel alloc]initWithFrame:CGRectMake(19,i * (MaxLableHeight+10)+95,70,MaxLableHeight)];
        titleLable.text = titleArray[i];
        [titleLable setTextColor:[UIColor colorWithHexString:@"#404040"]];
        titleLable.font = [UIFont systemFontOfSize:15];
        [self.enrollView addSubview:titleLable];
    }
    for (int i=0; i<4; i++) {
        UILabel *contentLable = [[UILabel alloc]initWithFrame:CGRectMake(89,i * (MaxLableHeight+10)+95,SCREEN_WIDTH *0.6,MaxLableHeight)];
        contentLable.backgroundColor = [UIColor whiteColor];
        contentLable.font = [UIFont systemFontOfSize:15];
        [self.infoArray addObject:contentLable];
        [self.enrollView addSubview:contentLable];
    }
}

#pragma mark 选择宣言
-(void)addSelectButton{
    for (int i=0; i<3; i++) {
        UIButton *selectButton = [[UIButton alloc]initWithFrame:CGRectMake(50,(i+5) * (MaxLableHeight+10)+95,25, 25)];
        selectButton.tag = i+10;
        [selectButton setBackgroundImage:[UIImage imageNamed:@"enroll_select_n"] forState:UIControlStateNormal];
        [selectButton setBackgroundImage:[UIImage imageNamed:@"enroll_select_p"] forState:UIControlStateSelected];
        if (i==0) {
            selectButton.selected = YES;
            self.selectBut = selectButton;
        }
        [self.ButtonArray addObject:selectButton];
        [self.enrollView addSubview:selectButton];
        [selectButton addTarget:self action:@selector(ClickSelectButtonIndex:) forControlEvents:UIControlEventTouchUpInside];
        
        UITextField * selectTextfield = [[UITextField alloc]initWithFrame:CGRectMake(90, (i+5) * (MaxLableHeight+10)+95-2, SCREEN_WIDTH * 0.6, MaxLableHeight)];
        selectTextfield.tag = i +20;
        selectTextfield.delegate = self;
        selectTextfield.textAlignment = NSTextAlignmentCenter;
        selectTextfield.textColor = [UIColor colorWithHexString:@"#000000"];
        selectTextfield.font = [UIFont systemFontOfSize:14];
        selectTextfield.text = self.contentArray[i];
        selectTextfield.layer.borderWidth = 1;
        selectTextfield.layer.cornerRadius = 5;
        selectTextfield.layer.borderColor = RGB(111, 202, 224).CGColor;
        selectTextfield.backgroundColor = [UIColor colorWithHexString:@"#FFFFFF"];
        [self.textfiledArray addObject:selectTextfield];
        [self.enrollView addSubview:selectTextfield];
    }
    UIButton *firmButton = [[UIButton alloc]initWithFrame:CGRectMake(60,8.2 * (MaxLableHeight+10)+110,SCREEN_WIDTH-120, 40)];
    firmButton.backgroundColor = RGB(253, 189, 74);
    firmButton.layer.cornerRadius = 20;
    firmButton.titleLabel.font = [UIFont boldSystemFontOfSize:15];
    [firmButton setTitle:@"确认报名" forState:UIControlStateNormal];
    [self.enrollView addSubview:firmButton];
    [firmButton addTarget:self action:@selector(ClickFirmButtons) forControlEvents:UIControlEventTouchUpInside];
}

#pragma mark 宣言选中按钮
-(void)ClickSelectButtonIndex:(UIButton *)sender{
    for (UIButton *btton in self.ButtonArray) {
        btton.selected = NO;
    }
    sender.selected = YES;
    NSInteger index = sender.tag - 10;
    UITextField *sloganTextField = (UITextField *)self.textfiledArray[index];
    self.sloganStr = sloganTextField.text;
    NSLog(@"slogan = %@",sloganTextField.text);
}

-(void)textFieldDidBeginEditing:(UITextField *)textField{
    for (UIButton *btton in self.ButtonArray) {
        btton.selected = NO;
    }
    if (textField.tag == 20) {
        UIButton *button =(UIButton *)self.ButtonArray[0];
        button.selected = YES;
    }else if (textField.tag ==21){
        UIButton *button =(UIButton *)self.ButtonArray[1];
        button.selected = YES;
    }else{
        UIButton *button =(UIButton *)self.ButtonArray[2];
        button.selected = YES;
    }
}
-(void)textFieldDidEndEditing:(UITextField *)textField{
    self.sloganStr = textField.text;
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}
#pragma mark 点击确认按钮
-(void)ClickFirmButtons{
    NSLog(@"确认");
//    YYaoViewController *yyvc = [[YYaoViewController alloc]init];
//    yyvc.hidesBottomBarWhenPushed = YES;
//    [self.navigationController pushViewController:yyvc animated:YES];
    
//    [self.baoMingView removeFromSuperview];
//    _scrolloView.contentSize = CGSizeMake(SCREEN_WIDTH,SCREEN_WIDTH*2.1+30);
//    ZCRankingDeatailView *rankingView = [[ZCRankingDeatailView alloc]initWithFrame:CGRectMake(0, 192,SCREEN_WIDTH,SCREEN_HEIGHT)];
//    [self.scrolloView addSubview:rankingView];
    
    
    if (ImgArray.count>0) {
        NSLog(@"task33");
         [GMDCircleLoader setOnView:self.view withTitle:@"努力加载中..." animated:YES];
        [NetworkManager requestAcsuzhouXwaImageUploadmid:UserModel.mid password:UserModel.password image:ImgArray success:^(NSData *data) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            NSString *str = [NSString stringWithFormat:@"%@",[dic objectForKey:@"content"]];
            NSLog(@"上传图片-图片id = %@ , slogan = %@",str,self.sloganStr);
            
            [NetworkManager requestAcsuzhouXwaSubmitmid:UserModel.mid password:UserModel.password thumb_id:str slogan:self.sloganStr success:^(NSDictionary *dictResponse) {
                NSString *errStr = [NSString stringWithFormat:@"%@",[dictResponse objectForKey:@"err"]];
                NSString *msgStr = [NSString stringWithFormat:@"%@",[dictResponse objectForKey:@"msg"]];
                self.voteStr = [NSString stringWithFormat:@"%@",[dictResponse objectForKey:@"content"]];
                if ([errStr isEqualToString:@"0"]) {
                    [[[iToast makeText:@"报名成功"]setGravity:iToastGravityCenter] show];
                    [self requestVotedetail];//请求学生信息
                }else{
                    [GMDCircleLoader hideFromView:self.view animated:YES];
                    [[[iToast makeText:msgStr]setGravity:iToastGravityCenter] show];
                }
            } failure:^(NSError *error) {
                [GMDCircleLoader hideFromView:self.view animated:YES];
            }];
             } failure:^(NSError *error) {
            [GMDCircleLoader hideFromView:self.view animated:YES];
        }];
    }else{
        NSLog(@"task44");
        [[[iToast makeText:@"请上传图片"]setGravity:iToastGravityCenter] show];
    }
}

#pragma mark 报名成功后-获取改学生的信息详情
-(void)requestVotedetail{
    NSLog(@"sdfs");
    [NetworkManager requestAcsuzhouXwaVoteDetailmid:UserModel.mid password:UserModel.password sid:self.voteStr success:^(NSDictionary *dictResponse) {
          [GMDCircleLoader hideFromView:self.view animated:YES];
        if ([[dictResponse objectForKey:@"content"] isKindOfClass:[NSDictionary class]]) {
            NSDictionary *dict= (NSDictionary *)[dictResponse objectForKey:@"content"];
            ZCRankingListModelContent *List = [ZCRankingListModelContent modelObjectWithDictionary:dict];
            if (self.baoMingView) {
                [self.baoMingView removeFromSuperview];
            }
                _scrolloView.contentSize = CGSizeMake(SCREEN_WIDTH,SCREEN_WIDTH*2.1);
                ZCRankingDeatailView *rankingView = [[ZCRankingDeatailView alloc]initWithFrame:CGRectMake(0, 192,SCREEN_WIDTH,SCREEN_HEIGHT)andDetail:List];
                [self.scrolloView addSubview:rankingView];
            rankingView.shareClick = ^{
                ActionView *action = [[ActionView alloc]initWithFrame:CGRectZero];
                action.isweb =3;
                action.pid = List.contentIdentifier;
                [action showInView:self.view];
            };
//            [self.scrolloView setContentOffset:CGPointMake(0,-64) animated:YES];
        }
    } failure:^(NSError *error) {
        [GMDCircleLoader hideFromView:self.view animated:YES];
    }];
}
- (void)addLabelTitle {
    [self.enrollView addSubview:self.labelTitle];
    [self.labelTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.enrollView.top).with.offset(5);
        make.height.mas_equalTo(@(30));
        make.width.mas_equalTo(@(70));
        make.left.mas_equalTo(@(19));
    }];
}

- (UILabel *)labelTitle {
    if (!_labelTitle) {
        _labelTitle = [[UILabel alloc] init];
        [_labelTitle setTextColor:[UIColor colorWithHexString:@"#404040"]];
        _labelTitle.font = [UIFont systemFontOfSize:15];
        _labelTitle.text = @"上传照片: ";
    }
    return _labelTitle;
}

-(UIScrollView *)scrolloView{
    if (!_scrolloView) {
        _scrolloView = [[UIScrollView alloc]initWithFrame:CGRectZero];
        _scrolloView.showsHorizontalScrollIndicator = YES;
        _scrolloView.showsVerticalScrollIndicator = YES;
        _scrolloView.delegate = self;
        _scrolloView.contentSize = CGSizeMake(SCREEN_WIDTH,840+50);
        _scrolloView.bounces = NO;
    }
    return _scrolloView;
}

-(UIImageView *)imageView{
    if (!_imageView) {
        _imageView = [[UIImageView alloc]initWithFrame:CGRectZero];
        _imageView.image = [UIImage imageNamed:@"enroll_head"];
    }
    return _imageView;
}

-(NSArray *)contentArray{
    if (!_contentArray) {
        _contentArray = [NSArray arrayWithObjects:@"食品安全我做主!",@"我为食品安全代言!",@"食品安全靠大家!",nil];
    }
    return _contentArray;
}

-(NSMutableArray *)infoArray{
    if (!_infoArray) {
        _infoArray = [NSMutableArray arrayWithCapacity:0];
    }
    return _infoArray;
}

-(NSMutableArray *)textfiledArray{
    if (!_textfiledArray) {
        _textfiledArray = [NSMutableArray arrayWithCapacity:0];
    }
    return _textfiledArray;
}
@end
